package models

import (
	"go_oauth2/constant"
	"log"
	"reflect"
	"time"
	"unsafe"
)

type OAuthToken struct {
	Token        string
	Expiration   string
	ClientId     string
	Username     string
	TokenType    string
	TokenScope   string
	RefreshToken string
}

/**
 * 用户Token是否失效
 * @method IsTokenExpired
 * @param [OAuthToken] token [保存的TokenObject]
 */
func (token *OAuthToken) IsTokenExpired() bool {
	expTime, err := time.ParseInLocation(constant.TimeFormat, token.Expiration, time.Local)
	if err != nil {
		log.Println("error while parse time")
		log.Println(err)
		return true
	}
	eu := expTime.Unix()
	nu := time.Now().Unix()
	gap := eu - nu
	if gap <= 0 {
		return true
	}
	return false
}

func OAuth2Bytes(authToken *OAuthToken) []byte {
	var size = int(unsafe.Sizeof(OAuthToken{}))
	var x reflect.SliceHeader
	x.Len = size
	x.Cap = size
	x.Data = uintptr(unsafe.Pointer(authToken))
	return *(*[]byte)(unsafe.Pointer(&x))
}

func Bytes2OAuth(b []byte) *OAuthToken {
	return (*OAuthToken)(unsafe.Pointer(
		(*reflect.SliceHeader)(unsafe.Pointer(&b)).Data,
	))
}
